package study;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * http://www.gupaoedu.com
 **/
public class NacosDataSourceInitFunc implements InitFunc{
    private String serverAddr="localhost:8848";
    private String groupId="SENTINEL_GROUP";
    private String dataId="spring-cloud-dubbo-sample22-sentinel-flow";
    private String namespace="";

    @Override
    public void init() throws Exception {
        System.out.println("===========================NacosDataSourceInitFunc===========================");
        loadNacosData();
    }
    private void loadNacosData() throws IOException {

        ClassPathResource fileResource = new ClassPathResource("application.properties");
        if(!fileResource.exists()){
            fileResource = new ClassPathResource("application.yml");
        }
        if(!fileResource.exists()){
            fileResource = new ClassPathResource("bootstrap.properties");
        }
        if(!fileResource.exists()){
            fileResource = new ClassPathResource("bootstrap.yml");
        }
        Properties properties = PropertiesLoaderUtils.loadProperties(fileResource);

        if(properties.get("sentinel.nacos.server-addr") !=null){
            serverAddr = (String) properties.get("sentinel.nacos.server-addr");
        }
        if(properties.get("sentinel.nacos.group-id") !=null){
            groupId = (String) properties.get("sentinel.nacos.group-id");
        }
        if(properties.get("sentinel.nacos.data-id") !=null){
            dataId = (String) properties.get("sentinel.nacos.data-id");
        }
        if(properties.get("sentinel.nacos.namespace") !=null){
            namespace = (String) properties.get("sentinel.nacos.namespace");
        }
        Properties properties_Nacos = new Properties();
        properties_Nacos.setProperty("serverAddr", serverAddr);
        properties_Nacos.setProperty("namespace",namespace);
        ReadableDataSource<String,List<FlowRule>> flowRuleDataSource=
                new NacosDataSource<>(properties_Nacos, groupId, dataId, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    }
}
